/**
 *                        .::::.
 *                      .::::::::.
 *                     :::::::::::
 *                  ..:::::::::::'
 *               '::::::::::::'
 *                 .::::::::::
 *            '::::::::::::::..
 *                 ..::::::::::::.
 *               ``::::::::::::::::
 *                ::::``:::::::::'        .:::.
 *               ::::'   ':::::'       .::::::::.
 *             .::::'      ::::     .:::::::'::::.
 *            .:::'       :::::  .:::::::::' ':::::.
 *           .::'        :::::.:::::::::'      ':::::.
 *          .::'         ::::::::::::::'         ``::::.
 *      ...:::           ::::::::::::'              ``::.
 *     ````':.          ':::::::::'                  ::::..
 *                        '.:::::'                    ':'````..
 * 
 * ----------------------
 * |  title: utils.js
 * |  version: v2.1.3
 * |  author: lw_yl
 * |  time: 2022.02.17
 * |  describe: 工具类（全平台端、浏览器端（wBrowser_XXXXX））
 * ----------------------
 */
/* 
 * ----------------------
 * |  全平台端
 * ----------------------
 */
/**
 * 正则类
 */
export const wRegexp = {
  /**
   * 手机号,默认移动手机号，1开头的11位数
   * @params String 手机号
   * @return Boolean
   */
  phone(str) {
    if (!(/^1\d{10}$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 邮箱
   * @params String 邮箱
   * @return Boolean
   */
  email(str) {
    if (!(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 纯数字
   * @params String 纯数字
   * @return Boolean
   */
  allNumber(str) {
    if (!(/^[0-9]*$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 正数 - (大于等于0的整数或小数)
   * @params String 正数
   * @return Boolean
   */
  positiveNumber(str) {
    if (!(/^(0|[1-9][0-9]*)(\.\d+)?$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 金额
   * @params String 金额
   * @return Boolean
   */
  price(str) {
    if (!(/((^[1-9]\d*)|^0)(\.\d{1,2}){0,1}$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 中文字符
   * @params String 中文字符
   * @return Boolean
   */
  character(str) {
    if (!(/^([\u4e00-\u9fa5])$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 身份证号
   * @params String 身份证号
   * @return Boolean
   */
  IDCard(str) {
    if (!(/^\d{15}|\d{18}$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 用户名 - (字母开头,4-16位,允许字母数字和下划线)
   * @params String 用户名
   * @return Boolean
   */
  username(str) {
    if (!(/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 密码 - (6-18位,只允许字母数字和下划线)
   * @params String 密码
   * @return Boolean
   */
  password(str) {
    if (!(/^[a-zA-Z0-9_]{6,18}$/.test(str))) {
      return false;
    } else {
      return true;
    }
  },

}
/**
 * 时间类
 */
export const wDate = {

  /**
   * 时间戳转换为时间
   * @params timestamp:时间戳  13位需要*1000
   * @return string
   */
  timestampToTime(timestamp) {
    var date = new Date(timestamp)
    var Y = date.getFullYear() + '-'
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())

    var res = Y + M + D + h + m + s
    return res
  },

  /**
   * 获取当前时间
   * @params void
   * @return string
   */
  getDateTimeNow() {
    var time = new Date();
    var day = ("0" + time.getDate()).slice(-2)
    var month = ("0" + (time.getMonth() + 1)).slice(-2)

    var hour = ("0" + time.getHours()).slice(-2)
    var minute = ("0" + time.getMinutes()).slice(-2)
    var second = ("0" + time.getSeconds()).slice(-2)

    var today = time.getFullYear() + "-" + (month) + "-" + (day) + " " + (hour) + ":" + (minute) + ":" + second
    return today
  },

  /**
   * 获取指定天数时间
   * @params int:昨日-1 今日0 明日1 以此类推
   * @return array
   */
  getDay(day) {
    var weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    var tWeek = today.getDay()

    const doHandleMonth = (month) => {
      var m = month;
      if (month.toString().length == 1) {
        m = "0" + month;
      }
      return m;
    }

    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);

    return [tYear, tMonth, tDate, weeks[tWeek]];
  }

}
/**
 * 类型类
 */
export const wType = {
  /**
   * （使用 Object.prototype.toString.call() 方法判断变量类型，tip:无法判断自定义对象类型）
   * Number数据类型是:[object Number]
   * Boolean数据类型是:[object Boolean]
   * String数据类型是:[object String]
   * Undefined数据类型是:[object Undefined]
   * Null数据类型是:[object Null]
   * Object数据类型是:[object Object]
   * RegExp数据类型是:[object RegExp]
   * Array数据类型是:[object Array]
   * Function数据类型是:[object Function]
   * 无法判断自定义对象类型:[object Object]
   * @params 值
   * @return String 返回值类型
   */
  wOPTC(params) {
    let wValType = Object.prototype.toString.call(params);
    if (wValType === '[object Number]') {
      return 'Number';
    }
    if (wValType === '[object Boolean]') {
      return 'Boolean';
    }
    if (wValType === '[object String]') {
      return 'String';
    }
    if (wValType === '[object Undefined]') {
      return 'Undefined';
    }
    if (wValType === '[object Null]') {
      return 'Null';
    }
    if (wValType === '[object RegExp]') {
      return 'RegExp';
    }
    if (wValType === '[object Array]') {
      return 'Array';
    }
    if (wValType === '[object Function]') {
      return 'Function';
    }
    if (wValType === '[object Object]') {
      return 'Object';
    }
  }
}
/* 
 * ----------------------
 * |  浏览器端（wBrowser_XXXXX）
 * ----------------------
 */
/**
 * 图片类
 */
export const wBrowser_image = {

  /**
   * 图片压缩
   * @params { base64:base64对象(必填)  width:宽度  height:高度  quality:质量  success:回调 }
   * @return void
   */
  compress(params) {
    const {
      base64,
      width,
      height,
      quality = 0.7,
      success = () => {}
    } = params;

    let img = new Image();
    img.src = base64;
    img.onload = function () {
      let that = this;

      let w = that.width,
        h = that.height,
        scale = w / h;
      w = width || w;
      h = height || (w / scale);

      let canvas = document.createElement('canvas');
      let ctx = canvas.getContext('2d');
      let anw = document.createAttribute("width");
      anw.nodeValue = w;
      let anh = document.createAttribute("height");
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w, h);

      success(canvas.toDataURL('image/png', quality));
    }
  },

  /**
   * base64转file
   * @params dataurl:base64对象  filename:文件名
   * @return file
   */
  dataURLtoFile(dataurl, filename) {
    let arr = dataurl.split(","),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {
      type: mime
    });
  },

  /**
   * base64转blob
   * @params dataurl:base64对象
   * @return blob
   */
  dataURLtoBlob(dataurl) {
    let arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
      type: mime
    });
  },

  /**
   * blob转base64
   * @params blob:blob对象 callback:回调
   * @return void
   */
  blobToDataURL(blob, callback) {
    let a = new FileReader();
    a.onload = function (e) {
      callback(e.target.result);
    }
    a.readAsDataURL(blob);
  }

}
/**
 * 浏览器类
 */

export const wBrowser_browser = {

  /**
   * 判断客户端pc,wap类型
   * @params void
   * @return int:1(PC) 0(WAP)
   */
  getClientType: function () {
    let sUserAgent = navigator.userAgent.toLowerCase();
    let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    let bIsMidp = sUserAgent.match(/midp/i) == "midp";
    let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    let bIsAndroid = sUserAgent.match(/android/i) == "android";
    let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
      return 0;
    } else {
      return 1;
    }
  },

  /**
   * 判断是不是微信内核
   * @params void
   * @return true false
   */
  changeWeChat() {
    return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
  },

  /**
   * 获取url参数
   * @params name:参数名
   * @return string | null
   */
  getLocationOption: function (name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null)
      return (r[2]);
    return null;
  },

  /**
   * 动态加载js脚本
   * @params src:地址 callback:加载完成回调
   * @return void
   */
  loadScript: function (src, callback) {
    var script = document.createElement('script');
    var head = document.getElementsByTagName('head')[0];
    script.type = 'text/javascript';
    script.charset = 'UTF-8';
    script.src = src;
    if (script.addEventListener) {
      script.addEventListener('load', function () {
        callback();
      }, false);
    } else if (script.attachEvent) {
      script.attachEvent('onreadystatechange', function () {
        var target = window.event.srcElement;
        if (target.readyState == 'loaded') {
          callback();
        }
      });
    }
    head.appendChild(script);
  },

  /**
   * 查询搜索记录
   * @params type:类别
   * @return Array
   */
  getSearchRecords: function (type = 0) {
    var list = JSON.parse(localStorage.getItem(`SEARCH-RECORDS-${type}`));
    !list && (list = []);
    return list;
  },

  /**
   * 添加搜索记录
   * @params type:类别 value:内容
   * @return Array
   */
  addSearchRecords: function (type = 0, value) {
    var list = JSON.parse(localStorage.getItem(`SEARCH-RECORDS-${type}`));
    !list && (list = []);
    list = list.slice(0, 9);
    list.unshift(value);
    list = [...new Set(list)];
    localStorage.setItem(`SEARCH-RECORDS-${type}`, JSON.stringify(list));
    return list;
  },

  /**
   * 清空搜索记录
   * @params type:类别
   * @return Array
   */
  emptySearchRecords: function (type = 0) {
    localStorage.removeItem(`SEARCH-RECORDS-${type}`)
    return [];
  }

}

// 整合为一个对象
export default {
  // 全平台端
  wRegexp,
  wDate,
  wType,
  // 浏览器端（wBrowser_XXXXX）
  wBrowser_image,
  wBrowser_browser,
}